
import axios from 'axios'
function removeNode(){
    const translateNode =  document.getElementById("translate-span")
    translateNode && document.body.removeChild(translateNode) 
}
export const translate=() => {
  document.addEventListener('mouseup', function (e) {
    if(e.target.id === 'translate-span') return
    removeNode()
    if(window.getSelection().toString().trim()){
        const queryText = window.getSelection().toString().trim() // 获取用户选中文字
        const span = document.createElement('span')
        span.style.background = '#1890ff'
        span.style.color = '#fff'
        span.style.border = '1px solid'
        span.style.borderRadius='2px'
        span.style.position='absolute'
        span.style.top=e.clientY+15+'px'
        span.style.left=e.clientX+'px'
        span.style.zIndex = 1000000
        span.id = 'translate-span'
        if(queryText){
            span.innerHTML='翻译'
        }
        document.body.appendChild(span)
        document.getElementById("translate-span").addEventListener('mousedown',(e)=>{
            e.preventDefault()
            axios.get(`http://localhost:9528/api/translate?text=${queryText}`)
            .then((res) => {
                const { dst } = res.data.trans_result[0]
            span.innerHTML = dst
            }).catch((e) => {
                console.log(e)
            }) 
        }) 
    }
   
  })
};

translate()


